package com.nazca.tvremote.event;

import org.json.JSONException;
import org.json.JSONObject;

import android.hardware.SensorEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;

public final class EventParser {
	
	public static Object parseJSON(String jsonString){
		Object obj = null;
		try {
			JSONObject json = new JSONObject(jsonString);
			
			String eventType = json.getString("EventType");
			JSONObject event = json.getJSONObject("Event");
			
			if("MotionEvent".equalsIgnoreCase(eventType)){
				obj = parseMotionEvent(event);
			} else if("KeyEvent".equalsIgnoreCase(eventType)){
				obj = parseKeyEvent(event);
			} else if("InputEvent".equalsIgnoreCase(eventType)){
				obj = parseInputEvent(event);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	
	private static String parseInputEvent(JSONObject event) {
		String inputEvent = null;
		try {
			inputEvent = event.getString("value");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return inputEvent;
	}
	
	public static MotionEvent parseMotionEvent(JSONObject event) {
		MotionEvent motionEvent = null;
		try {
			motionEvent = MotionEvent.obtain(
					event.getLong("downTime"), 
					event.getLong("eventTime"), 
					event.getInt("action"), 
					(Float)event.get("x"), 
					(Float)event.get("y"), 
					event.getInt("metaState")
					);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return motionEvent;
	}
	
	public static KeyEvent parseKeyEvent(JSONObject event){
		KeyEvent keyEvent = null;
		try {
			keyEvent = new KeyEvent(
					event.getLong("downTime"), 
					event.getLong("eventTime"), 
					event.getInt("action"), 
					event.getInt("code"),
					event.getInt("repeat"),
					event.getInt("metaState")
					);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return keyEvent;
	}
	
	public static SensorEvent parseSensorEvent(JSONObject event) {
		return null;
	}

}
